﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Errors;
using EffiProz.Core.Lib;

namespace EffiProz.Core
{
    public class SchemaObjectSet
    {
        public HashMap map;
        public int type;
        public SchemaManager manager;

        public SchemaObjectSet(int type)
        {

            this.type = type;

            switch (type)
            {

                case SchemaObjectTypes.VIEW:
                case SchemaObjectTypes.TABLE:
                case SchemaObjectTypes.SEQUENCE:
                case SchemaObjectTypes.CHARSET:
                case SchemaObjectTypes.DOMAIN:
                case SchemaObjectTypes.TYPE:
                case SchemaObjectTypes.COLLATION:
                case SchemaObjectTypes.PROCEDURE:
                case SchemaObjectTypes.FUNCTION:
                case SchemaObjectTypes.SPECIFIC_ROUTINE:
                case SchemaObjectTypes.ASSERTION:
                case SchemaObjectTypes.TRIGGER:
                    map = new HashMappedList();
                    break;

                case SchemaObjectTypes.CONSTRAINT:
                case SchemaObjectTypes.INDEX:
                    map = new HashMap();
                    break;
            }
        }

        public QNameManager.QName getName(String name)
        {

            switch (type)
            {

                case SchemaObjectTypes.VIEW:
                case SchemaObjectTypes.TABLE:
                case SchemaObjectTypes.SEQUENCE:
                case SchemaObjectTypes.CHARSET:
                case SchemaObjectTypes.DOMAIN:
                case SchemaObjectTypes.TYPE:
                case SchemaObjectTypes.COLLATION:
                case SchemaObjectTypes.PROCEDURE:
                case SchemaObjectTypes.SPECIFIC_ROUTINE:
                case SchemaObjectTypes.FUNCTION:
                case SchemaObjectTypes.ASSERTION:
                case SchemaObjectTypes.TRIGGER:
                    SchemaObject obj = ((SchemaObject)map.get(name));

                    return obj == null ? null
                                     : obj.getName();

                case SchemaObjectTypes.CONSTRAINT:
                case SchemaObjectTypes.INDEX:
                    {
                        return (QNameManager.QName)map.get(name);
                    }
                default:
                    return (QNameManager.QName)map.get(name);
            }
        }

        public SchemaObject getObject(String name)
        {

            switch (type)
            {

                case SchemaObjectTypes.VIEW:
                case SchemaObjectTypes.TABLE:
                case SchemaObjectTypes.SEQUENCE:
                case SchemaObjectTypes.CHARSET:
                case SchemaObjectTypes.DOMAIN:
                case SchemaObjectTypes.TYPE:
                case SchemaObjectTypes.COLLATION:
                case SchemaObjectTypes.PROCEDURE:
                case SchemaObjectTypes.SPECIFIC_ROUTINE:
                case SchemaObjectTypes.FUNCTION:
                case SchemaObjectTypes.ASSERTION:
                case SchemaObjectTypes.TRIGGER:
                    return (SchemaObject)map.get(name);

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "SchemaObjectSet");
            }
        }

        bool contains(String name)
        {
            return map.containsKey(name);
        }

        public void checkAdd(QNameManager.QName name)
        {

            if (map.containsKey(name.name))
            {
                int code = getAddErrorCode(name.type);

                throw Error.error(code, name.name);
            }
        }

        public void checkExists(String name)
        {

            if (!map.containsKey(name))
            {
                int code = getGetErrorCode(type);

                throw Error.error(code, name);
            }
        }

        public void add(SchemaObject _object)
        {

            QNameManager.QName name = _object.getName();

            if (type == SchemaObjectTypes.SPECIFIC_ROUTINE)
            {
                name = ((Routine)_object).getSpecificName();
            }

            if (map.containsKey(name.name))
            {
                int code = getAddErrorCode(name.type);

                throw Error.error(code, name.name);
            }

            Object value = _object;

            switch (name.type)
            {

                case SchemaObjectTypes.CONSTRAINT:
                case SchemaObjectTypes.INDEX:
                    value = name;
                    break;
            }

            map.put(name.name, value);
        }

        public void remove(String name)
        {
            map.remove(name);
        }

        public void removeParent(QNameManager.QName parent)
        {

            Iterator it = map.values().iterator();

            while (it.hasNext())
            {
                if (type == SchemaObjectTypes.TRIGGER
                        || type == SchemaObjectTypes.SPECIFIC_ROUTINE)
                {
                    SchemaObject obj = (SchemaObject)it.next();

                    if (obj.getName().parent == parent)
                    {
                        it.remove();
                    }
                }
                else
                {
                    QNameManager.QName name = (QNameManager.QName)it.next();

                    if (name.parent == parent)
                    {
                        it.remove();
                    }
                }
            }
        }

        public void rename(QNameManager.QName name, QNameManager.QName newName)
        {

            if (map.containsKey(newName.name))
            {
                int code = getAddErrorCode(name.type);

                throw Error.error(code, newName.name);
            }

            switch (newName.type)
            {

                case SchemaObjectTypes.VIEW:
                case SchemaObjectTypes.TABLE:
                case SchemaObjectTypes.SEQUENCE:
                case SchemaObjectTypes.CHARSET:
                case SchemaObjectTypes.COLLATION:
                case SchemaObjectTypes.PROCEDURE:
                case SchemaObjectTypes.FUNCTION:
                case SchemaObjectTypes.DOMAIN:
                case SchemaObjectTypes.TYPE:
                case SchemaObjectTypes.ASSERTION:
                case SchemaObjectTypes.TRIGGER:
                    {

                        int i = ((HashMappedList)map).getIndex(name.name);

                        if (i == -1)
                        {
                            int code = getGetErrorCode(name.type);

                            throw Error.error(code, name.name);
                        }

                        SchemaObject obj =
                      (SchemaObject)((HashMappedList)map).get(i);

                        obj.getName().rename(newName);
                        ((HashMappedList)map).setKey(i, name.name);

                        break;
                    }
                case SchemaObjectTypes.CONSTRAINT:
                case SchemaObjectTypes.INDEX:
                    {
                        map.remove(name.name);
                        name.rename(newName);
                        map.put(name.name, name);

                        break;
                    }
            }
        }

        static int getAddErrorCode(int type)
        {

            int code;

            switch (type)
            {

                case SchemaObjectTypes.VIEW:
                case SchemaObjectTypes.TABLE:
                case SchemaObjectTypes.SEQUENCE:
                case SchemaObjectTypes.CHARSET:
                case SchemaObjectTypes.DOMAIN:
                case SchemaObjectTypes.TYPE:
                case SchemaObjectTypes.COLLATION:
                case SchemaObjectTypes.PROCEDURE:
                case SchemaObjectTypes.FUNCTION:
                case SchemaObjectTypes.SPECIFIC_ROUTINE:
                case SchemaObjectTypes.CONSTRAINT:
                case SchemaObjectTypes.ASSERTION:
                case SchemaObjectTypes.INDEX:
                case SchemaObjectTypes.TRIGGER:
                    code = ErrorCode.X_42504;
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "SchemaObjectSet");
            }

            return code;
        }

       public static int getGetErrorCode(int type)
        {

            int code;

            switch (type)
            {

                case SchemaObjectTypes.VIEW:
                case SchemaObjectTypes.TABLE:
                case SchemaObjectTypes.SEQUENCE:
                case SchemaObjectTypes.CHARSET:
                case SchemaObjectTypes.DOMAIN:
                case SchemaObjectTypes.TYPE:
                case SchemaObjectTypes.CONSTRAINT:
                case SchemaObjectTypes.COLLATION:
                case SchemaObjectTypes.PROCEDURE:
                case SchemaObjectTypes.FUNCTION:
                case SchemaObjectTypes.SPECIFIC_ROUTINE:
                case SchemaObjectTypes.ASSERTION:
                case SchemaObjectTypes.INDEX:
                case SchemaObjectTypes.TRIGGER:
                    code = ErrorCode.X_42501;
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "SchemaObjectSet");
            }

            return code;
        }

        public static String getName(int type)
        {

            switch (type)
            {

                case SchemaObjectTypes.VIEW:
                    return Tokens.T_VIEW;

                case SchemaObjectTypes.TABLE:
                    return Tokens.T_TABLE;

                case SchemaObjectTypes.SEQUENCE:
                    return Tokens.T_SEQUENCE;

                case SchemaObjectTypes.CHARSET:
                    return Tokens.T_CHARACTER + ' ' + Tokens.T_SET;

                case SchemaObjectTypes.DOMAIN:
                    return Tokens.T_DOMAIN;

                case SchemaObjectTypes.TYPE:
                    return Tokens.T_TYPE;

                case SchemaObjectTypes.CONSTRAINT:
                    return Tokens.T_CONSTRAINT;

                case SchemaObjectTypes.COLLATION:
                    return Tokens.T_COLLATION;

                case SchemaObjectTypes.PROCEDURE:
                    return Tokens.T_PROCEDURE;

                case SchemaObjectTypes.FUNCTION:
                    return Tokens.T_FUNCTION;

                case SchemaObjectTypes.ASSERTION:
                    return Tokens.T_ASSERTION;

                case SchemaObjectTypes.INDEX:
                    return Tokens.T_INDEX;

                case SchemaObjectTypes.TRIGGER:
                    return Tokens.T_TRIGGER;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500, "SchemaObjectSet");
            }
        }

        public String[] getSQL(OrderedHashSet resolved, OrderedHashSet unresolved)
        {

            EfzArrayList list = new EfzArrayList();

            if (!(map is HashMappedList))
            {
                return null;
            }

            if (map.isEmpty())
            {
                return new string[0];
            }

            Iterator it = map.values().iterator();

            if (type == SchemaObjectTypes.FUNCTION || type == SchemaObjectTypes.PROCEDURE)
            {
                OrderedHashSet set = new OrderedHashSet();

                while (it.hasNext())
                {
                    RoutineSchema routine = (RoutineSchema)it.next();

                    for (int i = 0; i < routine.routines.Length; i++)
                    {
                        set.add(routine.routines[i]);
                    }
                }

                it = set.iterator();
            }

            while (it.hasNext())
            {
                SchemaObject obj = (SchemaObject)it.next();
                OrderedHashSet references = obj.getReferences();

                if (references != null)
                {
                    bool isResolved = true;

                    for (int j = 0; j < references.size(); j++)
                    {
                        QNameManager.QName name = (QNameManager.QName)references.get(j);

                        if (SqlInvariants.isSchemaNameSystem(name))
                        {
                            continue;
                        }

                        if (name.type == SchemaObjectTypes.COLUMN)
                        {
                            name = name.parent;
                        }

                        if (name.type == SchemaObjectTypes.CHARSET)
                        {

                            // some built-in character sets have no schema
                            if (name.schema == null)
                            {
                                continue;
                            }
                        }

                        if (!resolved.contains(name))
                        {
                            isResolved = false;

                            break;
                        }
                    }

                    if (!isResolved)
                    {
                        unresolved.add(obj);

                        continue;
                    }
                }

                resolved.add(obj.getName());

                if (obj.getType() == SchemaObjectTypes.TABLE)
                {
                    list.addAll(((Table)obj).getSQL(resolved, unresolved));
                }
                else
                {
                    list.add(obj.getSQL());
                }
            }

            String[] array = new String[list.size()];

            list.toArray(array);

            return array;
        }
    }
}
